// components/source-timeline/source-timeline.js
const dateFormatter = require('../../utils/dateFormatter')
const request = require('../../utils/request')
const Common = require('../../utils/common')

Component({
  properties: {
    // 是否显示弹窗
    show: {
      type: Boolean,
      value: false
    },
    // 销售凭证ID
    id: {
      type: [Number, String],
      value: null
    },
    // 显示模式：'full' 显示全部步骤，'partial' 只显示到检测
    mode: {
      type: String,
      value: 'full' // 'full' | 'partial'
    }
  },

  data: {
    timelineData: [], // 完整的时间轴数据
    displayData: [], // 根据模式过滤后的展示数据
    currentId: null, // 当前加载的ID，避免重复加载
    checkTypeDict: [], // 检测方式字典
    showMerchantDetail: false, // 显示商户详情弹窗
    merchantDetail: {} // 商户详细信息
  },

  lifetimes: {
    attached() {
      console.log('source-timeline: 组件attached');
    },
    ready() {
      console.log('source-timeline: 组件ready, show=', this.properties.show, 'id=', this.properties.id, 'mode=', this.properties.mode);
      // 加载检测方式字典
      this.loadCheckTypeDict();
      // 如果初始化时就是显示状态且有ID，立即加载
      if (this.properties.show && this.properties.id) {
        console.log('source-timeline: 初始化时立即加载数据');
        this.fetchSource(this.properties.id);
      }
    }
  },

  observers: {
    // 关键修复：同时监听 show 和 id，避免属性同时变化时读取到旧值
    'show, id': function(show, id) {
      console.log('source-timeline: observer 触发, show=', show, 'id=', id, 'currentId=', this.data.currentId);
      // 当弹窗显示时，如果有ID且不是当前已加载的ID，则调用接口
      if (show && id && this.data.currentId !== id) {
        console.log('source-timeline: 开始加载新数据, id=', id);
        this.fetchSource(id);
      } else {
        console.log('source-timeline: 跳过加载 - show=', show, 'id=', id, 'currentId=', this.data.currentId);
      }
    },
    'timelineData, mode': function(timelineData, mode) {
      console.log('source-timeline: observer timelineData/mode触发, 数据长度=', timelineData.length, 'mode=', mode);
      this.filterDisplayData();
    }
  },

  methods: {
    // 加载检测方式字典
    async loadCheckTypeDict() {
      try {
        const dictList = await Common.getDictData('check_type');
        this.setData({ checkTypeDict: dictList });
        console.log('source-timeline: 检测方式字典加载成功', dictList);
      } catch (err) {
        console.error('source-timeline: 加载检测方式字典失败', err);
      }
    },

    // 根据模式过滤显示的数据
    filterDisplayData() {
      const { timelineData, mode } = this.data;
      console.log('source-timeline: filterDisplayData 执行, mode=', mode, 'timelineData.length=', timelineData.length);
      
      if (mode === 'partial') {
        // 只显示到检测步骤（order, check, test）
        const filtered = timelineData.filter(item => 
          item.type === 'order' || item.type === 'check' || item.type === 'test'
        );
        console.log('source-timeline: partial 模式，过滤后数据长度=', filtered.length);
        this.setData({ displayData: filtered }, () => {
          console.log('source-timeline: displayData 设置完成, length=', this.data.displayData.length);
        });
      } else {
        // 显示全部步骤
        console.log('source-timeline: full 模式，使用全部数据');
        this.setData({ displayData: timelineData }, () => {
          console.log('source-timeline: displayData 设置完成, length=', this.data.displayData.length);
        });
      }
    },

    // 调用溯源接口并展示结果
    async fetchSource(id) {
      if (!id) {
        wx.showToast({ title: '未找到可溯源的ID', icon: 'none' });
        return;
      }

      console.log('source-timeline: 开始调用溯源接口, id=', id);

      try {
        // 确保字典数据已加载
        if (!this.data.checkTypeDict || this.data.checkTypeDict.length === 0) {
          await this.loadCheckTypeDict();
        }
        
        wx.showLoading({ title: '查询中...' });
        const res = await request.get('/admin-api/system/goods-sales-licens/source', { id });
        wx.hideLoading();
        
        console.log('source-timeline: 溯源接口返回结果', res);
        
        if (res.code !== 0 || !res.data || !res.data.list || res.data.list.length === 0) {
          wx.showToast({ title: '暂无溯源数据', icon: 'none' });
          this.triggerEvent('error', { message: '暂无溯源数据' });
          return;
        }

        const sourceData = res.data.list[0] || {};
        const timelineData = [];
        
        // 记录当前ID
        this.setData({ currentId: id });

        // 1. 预约时间 - 显示合格证图片
        const orderApply = sourceData.orderApplyWithCheckInfoVOS && sourceData.orderApplyWithCheckInfoVOS[0];
        if (orderApply && orderApply.orderApplySaveReqVO) {
          const order = orderApply.orderApplySaveReqVO;
          const planArriveTime = order.planArriveTime;
          if (planArriveTime) {
            const timestamp = typeof planArriveTime === 'number' ? planArriveTime : new Date(planArriveTime).getTime();
            const certificateImages = [];
            
            // 遍历所有商品，收集每个商品的合格证图片
            const applyDetails = orderApply.applyDetailSaveReqVOS || [];
            applyDetails.forEach(detail => {
              if (detail.certification) {
                certificateImages.push(...detail.certification.split(',').filter(img => img && img.trim()));
              }
            });

            timelineData.push({
              time: timestamp,
              timeText: dateFormatter.formatTimestamp(timestamp),
              title: '进场登记',
              type: 'order',
              certificates: certificateImages
            });
          }
        }

        // 2. 核验时间 - 显示核验人
        if (orderApply && orderApply.orderApplySaveReqVO) {
          const order = orderApply.orderApplySaveReqVO;
          const checkTime = order.checkTime;
          
          if (checkTime) {
            const timestamp = typeof checkTime === 'number' ? checkTime : new Date(checkTime).getTime();
            timelineData.push({
              time: timestamp,
              timeText: dateFormatter.formatTimestamp(timestamp),
              title: '门岗核验',
              type: 'check',
              checkUser: order.checkUser || '未知'
            });
          }
        }

        // 3. 检测时间 - 显示合格状态和检测指标结果
        if (orderApply && orderApply.orderApplySaveReqVO) {
          const order = orderApply.orderApplySaveReqVO;
          const testTime = order.testTime;
          if (testTime) {
            const timestamp = typeof testTime === 'number' ? testTime : new Date(testTime).getTime();
            const checkInfoList = orderApply.checkInfo || [];
            
            timelineData.push({
              time: timestamp,
              timeText: dateFormatter.formatTimestamp(timestamp),
              title: '抽样检测',
              type: 'test',
              expanded: true,
              testUserName: order.testUserName || '',
              testResults: checkInfoList.map(item => {
                const state = String(item.state || '').toLowerCase();
                let stateText = '';
                let stateColor = '#333';
                
                // 根据 state 字段映射为阴性/阳性
                if (state === 'positive') {
                  stateText = '阳性';
                  stateColor = '#F44336';
                } else if (state === 'negative') {
                  stateText = '阴性';
                  stateColor = '#07C160';
                } else if (state === 'repeat_negative') {
                  stateText = '复检阴性';
                  stateColor = '#07C160';
                }
                
                // 获取检测方式标签
                const checkTypeValue = item.checkType || '';
                const checkTypeLabel = checkTypeValue ? Common.getDictLabel(this.data.checkTypeDict, checkTypeValue) : '';
                
                // 获取送检时间
                let sendCheckTime = '';
                if (item.sendCheckTime) {
                  const sendTimestamp = typeof item.sendCheckTime === 'number' ? item.sendCheckTime : new Date(item.sendCheckTime).getTime();
                  sendCheckTime = dateFormatter.formatTimestamp(sendTimestamp);
                }
                
                return {
                  name: item.name || '',
                  stateText: stateText,
                  stateColor: stateColor,
                  checkType: checkTypeLabel || checkTypeValue || '',
                  sendCheckTime: sendCheckTime || ''
                };
              })
            });
          }
        }

        // 4. 销售凭证申请时间 - 显示预览按钮
        const salesInfo = sourceData.goodsSalesLicensSaveReqVO;
        if (salesInfo && salesInfo.createTime) {
          const timestamp = typeof salesInfo.createTime === 'number' ? salesInfo.createTime : new Date(salesInfo.createTime).getTime();
          const salesDetails = sourceData.salesLicensDetailSaveReqVOS || [];
          
          timelineData.push({
            time: timestamp,
            timeText: dateFormatter.formatTimestamp(timestamp),
            title: '销售合格证',
            type: 'sales',
            saleCode: salesInfo.saleCode || '',
            customerName: salesInfo.customerName || '',
            address: salesInfo.address || '',
            phone: salesInfo.phone || '',
            aboutOrder: salesInfo.aboutOrder || '',
            merchantId: salesInfo.merchantId || '',
            merchantName: salesInfo.merchantName || '',
            products: salesDetails.map(d => ({
              name: d.prodName || '',
              quantity: d.prodCount || ''
            })),
            isLicens: !!salesInfo.isLicens,
            isCheck: !!salesInfo.isCheck,
            createTime: salesInfo.createTime,
            okDate: salesInfo.okDate
          });
        }

        // 按时间顺序排列（最早的在最上面）
        timelineData.sort((a, b) => a.time - b.time);

        console.log('source-timeline: 解析后的时间轴数据', timelineData);
        console.log('source-timeline: 时间轴数据长度', timelineData.length);

        this.setData({ timelineData }, () => {
          console.log('source-timeline: timelineData 设置完成');
          console.log('source-timeline: 当前 show=', this.properties.show);
          console.log('source-timeline: 当前 displayData.length=', this.data.displayData.length);
        });
        this.triggerEvent('success', { data: timelineData });
      } catch (err) {
        wx.hideLoading();
        console.error('source-timeline: fetchSource error', err);
        wx.showToast({ title: '溯源查询失败', icon: 'none' });
        this.triggerEvent('error', { message: '溯源查询失败', error: err });
      }
    },

    // 切换检测结果展开/收起状态
    onToggleTestResults(e) {
      const index = e.currentTarget.dataset.index;
      const item = this.data.displayData[index];
      if (item && item.type === 'test') {
        this.setData({
          [`displayData[${index}].expanded`]: !item.expanded
        });
      }
    },

    // 预览合格证
    onPreviewCertificate(e) {
      const url = e.currentTarget.dataset.url;
      if (url) {
        const item = e.currentTarget.dataset.item;
        const urls = item.certificates || [url];
        wx.previewImage({
          current: url,
          urls: urls
        });
      }
    },

    // 预览销售凭证
    onPreviewSales(e) {
      const item = e.currentTarget.dataset.item;
      this.triggerEvent('previewSales', { item });
    },

    // 查看商户详情
    async showMerchantDetailModal(e) {
      const merchantId = e.currentTarget.dataset.merchantid;
      if (!merchantId) {
        wx.showToast({ title: '商户信息不存在', icon: 'none' });
        return;
      }
      
      wx.showLoading({ title: '加载中...' });
      try {
        const res = await request.get('/admin-api/system/merchant-info/get?id=' + merchantId);
        wx.hideLoading();
        
        if (res.code === 0 && res.data) {
          const merchantData = res.data;
          const licenseStr = merchantData.businessLicense || merchantData.license || '';
          const licenseList = licenseStr ? licenseStr.split(/[,，]/).map(url => url.trim()).filter(url => url) : [];
          
          this.setData({
            showMerchantDetail: true,
            merchantDetail: {
              name: merchantData.name || '',
              phone: merchantData.phone || '',
              address: merchantData.address || '',
              businessCategory: merchantData.businessCategory || merchantData.category || '',
              businessLicense: licenseStr,
              businessLicenseList: licenseList
            }
          });
        }
      } catch (err) {
        wx.hideLoading();
        console.error('获取商户信息失败:', err);
        wx.showToast({ title: '获取商户信息失败', icon: 'none' });
      }
    },

    // 关闭商户详情
    hideMerchantDetailModal() {
      this.setData({ showMerchantDetail: false });
    },

    // 预览营业执照
    previewBusinessLicense(e) {
      const licenseList = this.data.merchantDetail.businessLicenseList || [];
      if (licenseList.length === 0) {
        wx.showToast({ title: '暂无营业执照', icon: 'none' });
        return;
      }
      const index = e.currentTarget.dataset.index || 0;
      wx.previewImage({
        current: licenseList[index],
        urls: licenseList
      });
    },

    // 公开方法：打开弹窗并加载数据（供父组件调用）
    open(id) {
      console.log('source-timeline: open 方法被调用, id=', id);
      console.log('source-timeline: 当前 show=', this.properties.show);
      console.log('source-timeline: 当前 displayData.length=', this.data.displayData.length);
      if (!id) {
        wx.showToast({ title: '未找到可溯源的ID', icon: 'none' });
        return;
      }
      // 先清空旧数据，再加载新数据
      this.setData({
        timelineData: [],
        displayData: [],
        currentId: null
      }, () => {
        console.log('source-timeline: 旧数据已清空，准备加载新数据');
        // 加载新数据
        this.fetchSource(id);
      });
    },

    // 关闭弹窗
    onClose() {
      console.log('source-timeline: 关闭弹窗');
      // 清理数据，避免下次打开时显示旧数据
      this.setData({
        timelineData: [],
        displayData: [],
        currentId: null
      });
      this.triggerEvent('close');
    },

    // 阻止事件冒泡
    preventClose() {}
  }
});
